package hmvictor.jpql;

import java.io.File;
import java.io.IOException;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.filesystems.FileChooserBuilder;
import org.openide.modules.ModuleInstall;
import org.openide.util.Exceptions;
import org.openide.windows.WindowManager;

public class Installer extends ModuleInstall {

    @Override
    public void restored() {
        // TODO
    }

    @Override
    public boolean closing() {
        try {
            JPQLEditorTopComponent editor = (JPQLEditorTopComponent) WindowManager.getDefault().findTopComponent("JQPLEditorTopComponent");
            boolean cancelled = false;
            if (editor.isThereUnsavedContent()) {
                NotifyDescriptor.Confirmation msg = new NotifyDescriptor.Confirmation("There are unsaved content. Do you want to save it first?", NotifyDescriptor.YES_NO_CANCEL_OPTION,
                        NotifyDescriptor.QUESTION_MESSAGE
                );
                Object result = DialogDisplayer.getDefault().notify(msg);
                if (NotifyDescriptor.YES_OPTION.equals(result)) {
                    File file = editor.getFile();
                    if (file == null) {
                        File home = new File(System.getProperty("user.home"));
                        file = new FileChooserBuilder("user-dir").setTitle("Save File").setDefaultWorkingDirectory(home).setApproveText("Save").showSaveDialog();
                    }
                    if (file != null) {
                        editor.saveContent(file);
                    } else {
                        cancelled = true;
                    }
                } else if (NotifyDescriptor.CANCEL_OPTION.equals(result)) {
                    cancelled = true;
                }
            }
            return !cancelled;
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
            return false;
        }
    }

}
